package ar.edu.unicen.pladema.ui.model.g3d;

import java.util.HashMap;

public class Triangle implements Cloneable {
	private String vertex1Name;
	private String vertex2Name;
	private String vertex3Name;
	private Vertex vertex1;
	private Vertex vertex2;
	private Vertex vertex3;
	private Vertex normal=null;
	//private Vertex vertex1
	
	public void setVertex1(String sPoint1) {
		vertex1Name = sPoint1;
	}
	public void setVertex2(String sPoint2) {
		vertex2Name = sPoint2;
	}
	public void setVertex3(String sPoint3) {
		vertex3Name = sPoint3;
	}
	@Override
	public String toString() {
		return "(" + vertex1Name + "," + vertex2Name + ","+vertex3Name + ")";
	}
	public void setVertexes(HashMap<String, Vertex> vertexes) {
		this.vertex1 = vertexes.get(vertex1Name);
		this.vertex2 = vertexes.get(vertex2Name);
		this.vertex3 = vertexes.get(vertex3Name);
	}
	public Vertex getVertex1() {
		return vertex1;
	}
	public Vertex getVertex2() {
		return vertex2;
	}
	public Vertex getVertex3() {
		return vertex3;
	}
	public double getAVGZ() {
		return (vertex1.getDZ() + vertex2.getDZ() + vertex3.getDZ())/3;
	}
	public Vertex getNormal() {
		if (normal == null) {
			normal = cNormal();
		}
		return normal;
	}
	private Vertex cNormal() {
		Vertex result = new Vertex();
		Vertex s1 = new Vertex();
		s1.setDX(vertex2.getDX() - vertex1.getDX());
		s1.setDY(vertex2.getDY() - vertex1.getDY());
		s1.setDZ(vertex2.getDZ() - vertex1.getDZ());
		Vertex s2 = new Vertex();
		s2.setDX(vertex3.getDX() - vertex1.getDX());
		s2.setDY(vertex3.getDY() - vertex1.getDY());
		s2.setDZ(vertex3.getDZ() - vertex1.getDZ());
		//i aj*bk - ak*bj
		result.setDX((s1.getDY()*s2.getDZ())-(s1.getDZ()*s2.getDY()));
		//j - (ai*bk - ak*bi)
		result.setDY(-(s1.getDX()*s2.getDZ())+(s1.getDZ()*s2.getDX()));
		//k ai*bj - bi*aj
		result.setDZ((s1.getDX()*s2.getDY())-(s1.getDY()*s2.getDX()));
		return result;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		Triangle t = new Triangle();
		t.setVertex1(this.vertex1Name);
		t.setVertex2(this.vertex2Name);
		t.setVertex3(this.vertex3Name);
		return t;
	}
	public double getCosTheta(Vertex pluz) {
		Vertex thisNormalized = cNormal().getNormalized();
		double scalar = pluz.scalar(thisNormalized);
		double result = scalar / (thisNormalized.getModule() * pluz.getModule());
		return result;
	}
}
